﻿#include <utils/EventBus.h>

EventBus* EventBus::singleton = nullptr;

EventBus* EventBus::getInstance()
{
    if (EventBus::singleton == nullptr) {
        singleton = new EventBus();
    }
    return singleton;
}

void EventBus::subscribe(const IEvent& e, IEventFunc& func)
{
	_event.insert(std::make_pair(e, func));
}

void EventBus::unSubscribe(const IEvent& e)
{
	_event.erase(e);
}

typedef IEventMap::const_iterator constItr;
typedef std::pair<constItr, constItr> RetRange;	//查找结果

//todo 可能也需要锁,有可能出现正在notify的过程中出现注册与卸载,也可能同时notify的时候导致函数重入
//不在线程中变更应该不需要考虑
void EventBus::notify(const IEvent& e, const IEventParam& param)
{
	RetRange range = _event.equal_range(e);
	for (constItr itr = range.first; itr != range.second; ++itr)
	{
		IEventFunc f = itr->second;
		//todo 考虑是否使用线程去处理
		f(param);
	}
}

IEvent::IEvent(const std::string& name, int pri, SyncType type):_name(name), _priority(pri), _type(type)
{

}

IEvent& IEvent::operator=(const IEvent& other)
{
	if (this == &other)
	{
		return *this;
	}

	this->_name= other._name;
	this->_priority = other._priority;
	this->_type = other._type;
	return *this;
}

bool IEvent::operator==(const IEvent& other) const
{
	return this->_name == other._name &&
		this->_priority == other._priority &&
		this->_type == other._type;
}

bool IEvent::operator<(const IEvent& other) const
{
	if (this->_priority < other._priority)
	{
		return true;
	}
	return false;
}
